<template>
  <div>
    <div class="main">
      <div class="overview">班级平均年龄: {{ avgAge }}</div>

      <div class="tools-header">
        <button class="openModalBtn" @click="addStudent">添加学生</button>
        <button class="openModalBtn" @click="delSelectedStudent">删除</button>
        <div>
          <input
            v-model.trim="keyword"
            type="text"
            name="keyword"
            class="keyword"
            placeholder="Search by name"
          />
          <button @click="generateSearchData" type="button" class="searchBtn">搜索</button>
        </div>
      </div>

      <table class="studentTable">
        <thead>
          <tr>
            <th>
              <input
                v-model="isAllSelected"
                @change="changeSelectedAll"
                type="checkbox"
                class="selectAll"
              />
            </th>
            <th>ID</th>
            <th>Name</th>
            <th>Gender</th>
            <th>Hobbies</th>
            <th>Email</th>
            <th>Phone</th>
            <th>Age</th>
            <th>Created At</th>
            <th>Updated At</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="item in searchStudentArr" :key="item.id">
            <td>
              <input
                @change="changeSeletedItem"
                v-model="item.seleted"
                type="checkbox"
                class="selectAll"
              />
            </td>
            <td>{{ item.id }}</td>
            <td>{{ item.name }}</td>
            <td>{{ item.gender }}</td>
            <td>{{ item.hobbies }}</td>
            <td>{{ item.email }}</td>
            <td>{{ item.phone }}</td>
            <td>{{ item.age }}</td>
            <td>{{ item.create_at }}</td>
            <td>{{ item.update_at }}</td>
            <td>
              <button @click="editStuInfo(item)" class="editBtn" type="button">修改</button>
              <button @click="delStuInfo(item)" class="deleteBtn" type="button">删除</button>
            </td>
          </tr>
        </tbody>
      </table>

      <!-- Modal for adding/editing students -->
      <div v-show="isShowModel" class="studentModal modal" @click="closeModel">
        <StudentForm
          :student="modelInfo.type === 'edit' ? stuFormData : {} as IStudent"
          :isEditMode="modelInfo.type === 'edit'"
          :title="modelInfo.title"  
          @submit=" saveStuInfo"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, ref, onMounted } from 'vue'
import { getNowDateTime } from '@/utils'
import { uniqueId } from 'lodash'
import StudentForm from './studentForm.vue'

interface IStudent {
  id: string | number
  name: string
  gender: string
  hobbies: string
  email: string
  phone: string
  age: number | string
  create_at?: string
  update_at?: string
  seleted?: boolean
}

const isShowModel = ref(false)
const modelInfo = ref({
  type: 'add',
  title: '添加学生信息'  // 定义初始标题
})
const keyword = ref('')
const isAllSelected = ref(false)

const stuFormData = ref<IStudent>({
  id: '',
  age: '',
  email: '',
  gender: '',
  hobbies: '',
  name: '',
  phone: ''
})

const student = localStorage.getItem('student') as string;
const studentArr: Array<IStudent> = JSON.parse(student) || [];

const searchStudentArr = ref<Array<IStudent>>([])

const generateSearchData = () => {
  searchStudentArr.value = studentArr.filter((i) => i.name.includes(keyword.value))
}

const initAction = () => {
  generateSearchData()
}

const saveStuInfo = (student: IStudent) => {
  if (modelInfo.value.type === 'add') {
    studentArr.push({
      ...student,
      create_at: getNowDateTime(),
      update_at: getNowDateTime()
    })
  } else {
    const index = studentArr.findIndex((i) => i.id === student.id)
    studentArr[index] = {
      ...student,
      update_at: getNowDateTime()
    }
  }
  generateSearchData()
  changeSeletedItem()
  stusave()
  closeModel()
}

const addStudent = () => {
  modelInfo.value.type = 'add'
  modelInfo.value.title = '添加学生信息'
  isShowModel.value = true
}

const editStuInfo = (stu: IStudent) => {
  modelInfo.value.type = 'edit'
  modelInfo.value.title = '修改学生信息'
  stuFormData.value = { ...stu }
  isShowModel.value = true
}

const delStuInfo = (item: IStudent) => {
  const index = studentArr.findIndex((i) => i.id === item.id)
  studentArr.splice(index, 1)
  generateSearchData()
  changeSeletedItem()
  stusave()
}

const delSelectedStudent = () => {
  searchStudentArr.value.forEach((i) => {
    if (i.seleted) {
      delStuInfo(i)
    }
  })
}

const closeModel = () => {
  isShowModel.value = false
}

const changeSelectedAll = (event: Event) => {
  const checked = (event.target as HTMLInputElement).checked
  searchStudentArr.value.forEach((item: IStudent) => {
    item.seleted = checked
  })
}

const changeSeletedItem = () => {
  if (searchStudentArr.value.length > 0) {
    isAllSelected.value = searchStudentArr.value.every((i) => i.seleted)
  } else {
    isAllSelected.value = false
  }
}

const avgAge = computed(() => {
  return (
    Math.round(
      searchStudentArr.value.reduce(
        (previousValue, currentValue) => previousValue + Number(currentValue.age),
        0
      ) / searchStudentArr.value.length
    ) || 0
  )
})

const editId = () => {
  let a = 1;
  for (const key of studentArr) {
    key.id = `${a}`
    a++
  }
}

const stusave = () => {
  editId()
  localStorage.setItem('student', JSON.stringify(studentArr));
}

onMounted(() => {
  initAction()
})
</script>

<style lang="scss" scoped>
@import './style/demo1.scss';
</style>